package com.flesler.stickjoy.air.demo
{
	import com.flesler.stickjoy.controller.Controller;
	import com.flesler.stickjoy.controller.ControllerAxis;
	import com.flesler.stickjoy.controller.ControllerButton;
	import com.flesler.stickjoy.controller.ControllerComponent;
	
	import flash.events.Event;
	import flash.geom.Point;
	
	import mx.containers.Box;
	
	public final class ControlledBox extends Box
	{
		private static const SPEED:int = 3;
		
		private var controller:Controller;
		private var colorMap:Object = {};
		private var dir:Point;
		
		public function ControlledBox(controller:Controller)
		{
			this.controller = controller;
			
			init();
		}
		
		private function init():void
		{
			dir = new Point();
			
			width = 100;
			height = 100;
			paint();
			
			for each (var component:ControllerComponent in controller.components)
			{
				if (component.isAnalog)
					component.addEventListener(Event.CHANGE, changeSpeed);
				else
					component.addEventListener(Event.CHANGE, changeColor);
			}
			
			addEventListener(Event.ENTER_FRAME, moveBySpeed);
		}
		
		private function changeSpeed(e:Event):void
		{
			var axis:ControllerAxis = e.target as ControllerAxis;
			dir[axis.key] = axis.position;
		}
		
		private function changeColor(e:Event):void
		{
			var button:ControllerButton = e.target as ControllerButton;
			if (button.isDown)
				paint(button.key);
			else
				paint();
		}
		
		private function paint(key:String='default'):void
		{
			var color:uint = colorMap[key] || (colorMap[key] = Math.random()*0xFFFFFF);
			setStyle('backgroundColor', color);
		}
		
		private function moveBySpeed(e:Event):void
		{
			x += dir.x * SPEED;
			y += dir.y * SPEED;
		}
		
		public function destroy():void
		{
			for each (var component:ControllerComponent in controller.components)
			{
				component.removeEventListener(Event.CHANGE, changeSpeed);
				component.removeEventListener(Event.CHANGE, changeColor);
			}
			
			removeEventListener(Event.ENTER_FRAME, moveBySpeed);
			controller = null;
		}
	}
}